package org.jeecg.modules.bigdata.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.modules.bigdata.mapper.BigdataMapper;
import org.jeecg.util.Base64URL;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: 大数据-提取网页内容
 * @Author: scott
 * @Date:2019-12-12
 * @Version:V1.0
 */
@Slf4j
@RestController
@Api(tags = "大数据相关（任务管理）")
@RequestMapping("/big/data")
public class BigDataController  {

    static String subscriptionKey = "c21bd76a4662485682515ed3d1f6f5fd";
    static String host = "https://api.bing.microsoft.com";
    static String path = "/v7.0/images/search";
    static String searchTerm = "tropical ocean";

    @Resource
    private BigdataMapper bigdataMapper;

    @GetMapping(value = "/imageUrlToBase64")
    public Result<?> queryNewsList(@RequestParam(name="url") String url) {
        return Result.OK("data:image/jpeg;base64,"+ Base64URL.imageUrlToBase64(url));
    }

    /**
     *
     * @param type 0 新闻 1图片
     * @param key 关键词
     * @return
     */
    @AutoLog(value = "大数据-查询新闻信息")
    @ApiOperation(value="大数据-查询新闻信息", notes="大数据-查询新闻信息")
    @GetMapping(value = "/queryNewsList")
    public Result<?> queryNewsList(@RequestParam(name="type") String type, @RequestParam(name="key") String key,
                                   @RequestParam(name="count", required = false) String count,@RequestParam(name="offset", required = false) String offset,
                                   HttpServletRequest req) {
        String httpUrl = "";
        Object ob = "";
        if(type.equals("0")){
            httpUrl = "http://api.tianapi.com/generalnews/index?key=5b9a5bb416a1b05927abbfff337ee675&word="+key;
        }else if(type.equals("1")){
            URL url = null;
            try {
                url = new URL(host + path + "?q=" +  URLEncoder.encode(key, "UTF-8")+"&count="+count+"&offset="+offset);
            HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
            connection.setRequestProperty("Ocp-Apim-Subscription-Key", subscriptionKey);
            // receive JSON body
            InputStream stream = connection.getInputStream();
            String response = new Scanner(stream).useDelimiter("\\A").next();
            ob = (JSONObject) JSON.parseObject(response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(type.equals("0")) {
            String jsonResult = request(httpUrl);
            ob = (JSONArray) JSON.parseObject(jsonResult).get("newslist");
        }

        return Result.ok(ob);
    }



    /**
     * @param
     *            :请求接口
     *            :参数
     * @return 返回结果
     */
    public  String request(String httpUrl) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
//        httpUrl = httpUrl + "?" + httpArg;
//        httpUrl = httpUrl ;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 大数据-提取网页内容
     * @param url
     * @return
     */
    @AutoLog(value = "大数据-提取网页内容")
    @ApiOperation(value="大数据-提取网页内容", notes="大数据-提取网页内容")
    @GetMapping(value = "/extractUrl")
    public Result<?> extractUrl(@RequestParam(name="url") String url,
                                   HttpServletRequest req) {

        String httpUrl = "http://api.tianapi.com/txapi/htmltext/index?key=5b9a5bb416a1b05927abbfff337ee675&url="+url;
        String jsonResult = request(httpUrl);

        return Result.ok(JSON.parseObject(jsonResult).get("newslist"));
    }



    @ApiOperation(value="关键词热度", notes="关键词热度")
    @GetMapping(value = "/getHotKeyword")
    public Result<?> getHotKeyword() {
        return Result.OK(bigdataMapper.getHotKeyword());
    }




    @ApiOperation(value="新闻分布", notes="新闻分布")
    @GetMapping(value = "/getNewsDistribute")
    public Result<?> getNewsDistribute() {
        return Result.OK(bigdataMapper.getNewsDistribute());
    }

    @ApiOperation(value="实时文章", notes="实时文章")
    @GetMapping(value = "/getNews")
    public Result<?> getNews() {
        return Result.OK(bigdataMapper.getNews());
    }



    @ApiOperation(value="任务总览", notes="任务总览")
    @GetMapping(value = "/getTaskInfo")
    public Result<?> getTaskInfo() {

        Map<String,Object> result = new HashMap<String,Object>();
        Integer total  = bigdataMapper.getTaskTotal();
        Integer processing = bigdataMapper.getProcessing();
        Integer done = bigdataMapper.getDone();
        Integer xw = bigdataMapper.gexw();
        Integer gw = bigdataMapper.gegw();
        result.put("total",total);
        result.put("processing",processing);
        result.put("processingName","处理中");
        result.put("processingS","处理中");
        result.put("processingPer",processing/total*100);
        result.put("doneName","已办结");
        result.put("doneS","已办结");
        result.put("done",done);
        result.put("donePer",done/total*100);
        result.put("xwName","新闻网");
        result.put("xwS","新闻网");
        result.put("xw",xw);
        result.put("xwPer",xw/total*100);
        result.put("gw",gw);
        result.put("gwPer",gw/total*100);
        result.put("gwName","官网");
        result.put("gwS","官网");
        return Result.OK(result);
    }



    @ApiOperation(value="发文趋势", notes="发文趋势")
    @GetMapping(value = "/getTask7Days")
    public Result<?> getTask7Days() {
        return Result.OK(bigdataMapper.getTask7Days());
    }



    @ApiOperation(value="发文部门排行", notes="发文部门排行")
    @GetMapping(value = "/getTaskByDeparts")
    public Result<?> getTaskByDeparts() {
        return Result.OK(bigdataMapper.getTaskByDeparts());
    }

}
